package swing.dialog;

import api.DictionaryApi;
import beanInfo.MeaningInfo;
import beanInfo.WordInfo;
import beans.Meaning;
import beans.Word;
import client.UserSession;
import http.Response;
import model.ApiResultModel;
import myException.ServerConnectException;
import swing.customComp.HintJTextField;
import swing.customComp.CustomStyles;

import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.*;
import java.util.List;

/**
 * 添加单词、添加/修改单词释义的自定义对话框
 */
public class UpdateWordDialog extends JDialog{

    public final static int ADD_WORD = 1;
    public final static int ADD_MEANING = 2;
    public final static int UPDATE_MEANING = 3;

    private String getDialogTitle(int mode) {
        switch (mode) {
            case ADD_WORD :
                return "添加单词";
            case ADD_MEANING :
                return "添加释义";
            case UPDATE_MEANING :
                return "修改释义";
        }
        return "";
    }

    public int dialogMode;

    public long dialog_result = 0;
    public Meaning meaning;

    public JPanel contentPanel;

    public JLabel wordLabel;
    public HintJTextField wordFiled;
    public JLabel meaningLabel;
    public HintJTextField addMeaningFiled1;
    public List<HintJTextField> meaningFieldList;
    public JButton addButton;
    public JButton cancelButton;

    public UpdateWordDialog(JFrame parentFrame) {
        this(parentFrame, ADD_WORD, "");
    }

    public UpdateWordDialog(JFrame parentFrame, int mode, String word_string) {
        this(parentFrame, mode, word_string, null);
    }

    public UpdateWordDialog(JFrame parentFrame, int mode, String word_string, Meaning meaning) {
        super(parentFrame, true);
        this.dialogMode = mode;
        this.meaning = meaning;
        String title = getDialogTitle(mode);
        this.setTitle(title);
        this.setSize(400,300);
        this.setLocationRelativeTo(parentFrame);
        contentPanel = new JPanel();
        contentPanel.setLayout(null);
        initAllComponent();
        addAllComponent();
        if (dialogMode == ADD_MEANING || dialogMode == UPDATE_MEANING) {
            wordFiled.setText(word_string);
            wordFiled.setEditable(false);
            //使释义输入框获取焦点
            SwingUtilities.invokeLater(() -> addMeaningFiled1.requestFocusInWindow());
        } else {
            //设置启动焦点
            SwingUtilities.invokeLater(() -> contentPanel.requestFocusInWindow());
        }
        if (dialogMode == UPDATE_MEANING) {
            addMeaningFiled1.setText(meaning.getWord_meaning());
        }
        meaningFieldList = new ArrayList<>();
        meaningFieldList.add(addMeaningFiled1);
        this.setContentPane(contentPanel);
    }

    private void initAllComponent() {
        //静态文本
        wordLabel = new JLabel("单词：");
        Font staticTextFont = new Font("宋体", Font.BOLD,17);
        wordLabel.setFont(staticTextFont);
        wordLabel.setBounds(10,10,200,20);
        //添加单词输入框
        wordFiled = new HintJTextField();
        if (dialogMode == ADD_WORD) {
            wordFiled.setHintText("请输入要添加的单词（1-255个字母或空格）");
        }
        wordFiled.setBounds(10, 40, 300, 30);
        wordFiled.addKeyListener(new KeyAdapter() {
            @Override
            public void keyTyped(KeyEvent e) {
                super.keyTyped(e);
                int keyChar = e.getKeyChar();
                //目前只支持字母和空格
                if ((keyChar >= 'a'&& keyChar <= 'z') || (keyChar>= 'A'&& keyChar <= 'Z') || keyChar == ' ') {

                } else {
                    e.consume();
                }
            }
        });
        wordFiled.setFont(CustomStyles.inputFont);
        //静态文本
        meaningLabel = new JLabel("单词释义：");
        meaningLabel.setFont(staticTextFont);
        meaningLabel.setBounds(10,80,200,20);
        //添加释义输入框
        addMeaningFiled1 = new HintJTextField();
        addMeaningFiled1.setHintText("请输入释义（1-255个字符）");
        addMeaningFiled1.setBounds(10, 110, 300, 30);
        addMeaningFiled1.setFont(CustomStyles.inputFont);
        //添加按钮
        if (dialogMode == UPDATE_MEANING) {
            addButton = new JButton("修改");
            addButton.addActionListener(e -> {
                updateMeaning(meaning.getId(), addMeaningFiled1.getText().trim());
            });
        } else {
            addButton = new JButton("添加");
            addButton.addActionListener(e -> {
                String word = wordFiled.getText().trim();
                String meaning1 = addMeaningFiled1.getText().trim();
                List<String> meaningList = new ArrayList<>();
                meaningList.add(meaning1);
                add(word, meaningList);
            });
        }
        addButton.setBounds(20, 180, 100, 30);
        //取消按钮
        cancelButton = new JButton("取消");
        cancelButton.setBounds(200, 180, 100, 30);
        cancelButton.addActionListener(e -> this.dispose());
    }

    private void addAllComponent() {
        contentPanel.add(wordLabel);
        contentPanel.add(addButton);
        contentPanel.add(wordFiled);
        contentPanel.add(meaningLabel);
        contentPanel.add(addMeaningFiled1);
        contentPanel.add(addButton);
        contentPanel.add(cancelButton);
    }

    public void add(String wordStr, List<String> meaningList) {
        try {
            if (!WordInfo.isLengthLegal(wordStr)) {
                showMessageDialog("单词长度超出限制！");
                return;
            }
            for (String meaningStr : meaningList) {
                if (!MeaningInfo.isLengthLegal(meaningStr)) {
                    showMessageDialog("释义长度超出限制！");
                    return;
                }
            }
            Response response = DictionaryApi.add(UserSession.LoginUser(), dialogMode, wordStr, meaningList);
            ApiResultModel<Word> apiResultModel = ApiResultModel.fromJson(response.getBody(), Word.class);
            if (apiResultModel.getCode() == ApiResultModel.SUCCESS_CODE) {
                showMessageDialog("添加成功！");
                Word word = apiResultModel.getResult();
                dialog_result = word.getId();
                //刷新个人主页成就列表
                UserSession.addAchievement(dialogMode==ADD_WORD ? 1 : 0, meaningList.size(), 0);
                this.dispose();
            } else {
                showMessageDialog(apiResultModel.getMessage());
            }
        } catch (ServerConnectException e) {
            showMessageDialog("服务器连接失败！");
            e.printStackTrace();
        }
    }

    public void updateMeaning(long meaning_id, String update_meaning) {
        try {
            if (!MeaningInfo.isLengthLegal(update_meaning)) {
                showMessageDialog("释义长度超出限制！");
                return;
            }
            Response response = DictionaryApi.update_meaning(UserSession.LoginUser(), meaning_id, update_meaning);
            ApiResultModel apiResult = ApiResultModel.fromJson(response.getBody());
            showMessageDialog(apiResult.getMessage());
            if (apiResult.getCode() == ApiResultModel.SUCCESS_CODE) {
                dialog_result = meaning_id;
                //刷新个人主页成就列表
                UserSession.addAchievement(0, 0, 1);
                this.dispose();
            }
        } catch (ServerConnectException e) {
            showMessageDialog("服务器连接失败！");
            e.printStackTrace();
        }
    }

    /**
     * 添加/修改成功则返回单词的id，否则返回0
     */
    public long showDialog() {
        this.setVisible(true);
        //模态对话框 只有当对话框销毁时才会执行到下面这一句
        return dialog_result;
    }

    private void showMessageDialog(String message) {
        JOptionPane.showMessageDialog(contentPanel, message);
    }
}
